import { Button, ButtonGroup, styled } from '@mui/material'
import { useContext, useEffect, useReducer, useState } from 'react'
import { Actions } from '../../store/reducer'
import { AppContext } from '../../store/storeProvider'

export const DEFAULT_PAGE = 1
export const DEFAULT_ITEMS_PER_PAGE = 12

type TPagination = {
	page?: number
	selectedPage?: number
	itemsPerPage?: number
}

const StyledButton = styled(Button, {
	shouldForwardProp: (props) => props !== 'sortBy' && props !== 'selectedPage',
})<Pick<TPagination, 'page' | 'selectedPage'>>(({ page, selectedPage }) => ({
	textTransform: 'none',
	color: page === selectedPage ? '#1A1A1A' : '#7B8E98',
	fontFamily: 'Nunito',
	fontSize: '14px',
	border: '0',
}))

const Pagination = () => {
	const { state, dispatch } = useContext(AppContext)

	function reducePages() {
		return Array.from(
			{ length: state.pagination.maxPage },
			(_, i) => i + 1
		).slice(selectedPage - 1, selectedPage + 2)
	}

	const [selectedPage, setSelectedPage] = useState(
		state.pagination.selectedPage
	)
	const [pages, setPages] = useReducer(reducePages, [
		state.pagination.selectedPage,
	])

	useEffect(() => {
		dispatch({ type: Actions.SET_PAGE, selectedPage: selectedPage })
		setPages()
	}, [dispatch, selectedPage, state.pagination.maxPage])

	return (
		<ButtonGroup>
			<StyledButton
				selectedPage={selectedPage}
				onClick={() => setSelectedPage(1)}
			>
				{'< Назад'}
			</StyledButton>
			{pages.map((page) => (
				<StyledButton
					key={page}
					page={page}
					selectedPage={selectedPage}
					onClick={() => setSelectedPage(page)}
				>
					{page}
				</StyledButton>
			))}
			<StyledButton
				selectedPage={selectedPage}
				onClick={() => setSelectedPage(1)}
			>
				...
			</StyledButton>
			<StyledButton
				selectedPage={selectedPage}
				onClick={() => setSelectedPage(1)}
			>
				{'Вперёд >'}
			</StyledButton>
		</ButtonGroup>
	)
}

export default Pagination
